package org.ala.tcp_feign_client.handler.login;

import org.ala.tcp_feign_client.context.TcpFeignClientContext;
import org.ala.tcp_feign_common.config.AttrbuteKeyNamespace;
import org.ala.tcp_feign_common.enums.TcpFeignMessageTypeEnums;
import org.ala.tcp_feign_common.handler.IByteMessageAction;
import org.ala.tcp_feign_common.logs.LoggerFactory;
import org.ala.tcp_feign_common.msg.login.LoginACKByteMessage;
import org.slf4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;


/**
 * 登录回执action
 * 
 * @author 骆毅(ala)
 * @date 2024年4月20日
 */
public class LoginACKByteMessageAction implements IByteMessageAction<LoginACKByteMessage> {
	
	
	static Logger log = LoggerFactory.getLogger("tcp-feign", "client");
	

	@Override
	public TcpFeignMessageTypeEnums type() {
		return TcpFeignMessageTypeEnums.LOGIN_ACK;
	}

	@Override
	public void action(ChannelHandlerContext ctx, LoginACKByteMessage msg) {
		if (msg.isSuccess()) {
			ctx.channel().attr(AttributeKey.valueOf(AttrbuteKeyNamespace.LOGIN)).set(true);
			Runnable runnable = (Runnable) ctx.channel().attr(AttributeKey.valueOf(AttrbuteKeyNamespace.LOGIN_SUCCESS)).get();
			runnable.run();
			
			log.info("[LoginACKByteMessageAction action] 收到登录回执，登录成功。" + ctx.channel().id());
		} else {
			ctx.channel().attr(AttributeKey.valueOf(AttrbuteKeyNamespace.LOGIN)).set(false);
			log.warn("[LoginACKByteMessageAction action] 收到登录回执，登录失败。" + ctx.channel().id());
			
			String host = TcpFeignClientContext.hostFromChannel(ctx.channel());
			Integer port = TcpFeignClientContext.portFromChannel(ctx.channel());
			String suffix = TcpFeignClientContext.suffixFromChannel(ctx.channel());
			String username = TcpFeignClientContext.userFromChannel(ctx.channel());
			String password = TcpFeignClientContext.passwordFromChannel(ctx.channel());
			TcpFeignClientContext.instance().close(host, port, suffix, username, password);
		}
	}

}
